import re
import json
import time
import hashlib
import requests
from html import unescape
from base64 import b64decode
from urllib.parse import unquote

class HUYA():
    def getInfos(self, params):
        header = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36'
        }
        if 'pos' in params:
            pos = int(params['pos'])
        else:
            pos = 0
        rid = params['rid']
        url = 'https://www.huya.com/' + rid
        r = requests.get(url, headers=header, timeout=15)
        streamInfo = re.findall(r'stream: ([\s\S]*?)\n', r.text)
        if (len(streamInfo) > 0):
            liveData = json.loads(streamInfo[0])
        else:
            streamInfo = re.findall(r'"stream": "([\s\S]*?)"', r.text)
            if (len(streamInfo) > 0):
                liveDataBase64 = streamInfo[0]
                liveData = json.loads(str(base64.b64decode(liveDataBase64), 'utf-8'))
            else:
                raise Exception('错误：未找到直播地址')
        streamInfoList = liveData['data'][0]['gameStreamInfoList']
        urlList = []
        for streamInfo in streamInfoList:
            hlsUrl = streamInfo['sHlsUrl'] + '/' + streamInfo['sStreamName'] + '.' + streamInfo['sHlsUrlSuffix']
            srcAntiCode = unescape(streamInfo['sHlsAntiCode'])
            c = srcAntiCode.split('&')
            c = [i for i in c if i != '']
            n = {i.split('=')[0]: i.split('=')[1] for i in c}
            fm = unquote(n['fm'])
            u = b64decode(fm).decode('utf-8')
            hashPrefix = u.split('_')[0]
            ctype = n.get('ctype', '')
            txyp = n.get('txyp', '')
            fs = n.get('fs', '')
            t = n.get('t', '')
            seqid = str(int(time.time() * 1e3 + 1463993859134))
            wsTime = hex(int(time.time()) + 3600).replace('0x', '')
            hash = hashlib.md5('_'.join([hashPrefix, '1463993859134', streamInfo['sStreamName'], hashlib.md5((seqid + '|' + ctype + '|' + t).encode('utf-8')).hexdigest(), wsTime]).encode('utf-8')).hexdigest()
            url = "{}?wsSecret={}&wsTime={}&seqid={}&ctype={}&ver=1&txyp={}&fs={}&ratio=&u=1463993859134&t={}&sv=2107230339".format(hlsUrl, hash, wsTime, seqid, ctype, txyp, fs, t)
            urlList.append(url)
        if pos > len(urlList):
            url = urlList[len(urlList)]
        else:
            url = urlList[pos]
        return url

